package com.gxpt.app.view;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.Poi;
import com.google.gson.Gson;
import com.gxpt.app.AppUtils;
import com.gxpt.app.BaseActivity;
import com.gxpt.app.Constant;
import com.gxpt.app.MessageEvent;
import com.gxpt.app.MyApp;
import com.gxpt.app.R;
import com.gxpt.app.adapter.city_sub_Adapter;
import com.gxpt.app.bean.getregion_bean;
import com.gxpt.app.codes.service.LocationService;
import com.utils.T;
import com.utils.logger.Logger;
import com.utils.okhttputils.HttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;


/**
 * Created by dufeng on 2017/8/4.
 */

@ContentView(R.layout.activity_city_select_2)
public class Activity_city_select_2 extends BaseActivity {

    @ViewInject(R.id.toback)
    Button toback;

    @ViewInject(R.id.txt_title)
    TextView txt_title;

    @ViewInject(R.id.loc_info)
    TextView loc_info;


    @ViewInject(R.id.type_main)
    LinearLayout type_main;
//
    @ViewInject(R.id.recycler_sub)
    RecyclerView recycler_sub;

    String main_id="";
    String main_name="";
    city_sub_Adapter mCity_sub_Adapter;
    List<getregion_bean.getregion> data_sub = new ArrayList<getregion_bean.getregion>();

    String action_str ="";

    LocationService locationService;

    String baidu_loc_info="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle b = getIntent().getBundleExtra("DATA");
        if(b != null){
            action_str = b.getString("FORM_");
        }
        x.view().inject(this);
        initBaidu();
        initView();
        initData();
    }



    private void initBaidu(){
//        if(action_str.equals("Fragment_home")){

            Logger.i("开始定位。。。");
            locationService = ((MyApp) getApplication()).locationService;
            //获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
            locationService.registerListener(mListener);

            locationService.setLocationOption(locationService.getDefaultLocationClientOption());

//            locationService.setLocationOption(locationService.getOption());

            locationService.start();// 定位SDK


//        }
    }

    /*****
     *
     * 定位结果回调，重写onReceiveLocation方法，可以直接拷贝如下代码到自己工程中修改
     *
     */
    private BDAbstractLocationListener mListener = new BDAbstractLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // TODO Auto-generated method stub
            Logger.i(""+location.toString());
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                StringBuffer sb = new StringBuffer(256);
                sb.append("time : ");
                /**
                 * 时间也可以使用systemClock.elapsedRealtime()方法 获取的是自从开机以来，每次回调的时间；
                 * location.getTime() 是指服务端出本次结果的时间，如果位置不发生变化，则时间不变
                 */
                sb.append(location.getTime());
                sb.append("\nlocType : ");// 定位类型
                sb.append(location.getLocType());
                sb.append("\nlocType description : ");// *****对应的定位类型说明*****
                sb.append(location.getLocTypeDescription());
                sb.append("\nlatitude : ");// 纬度
                sb.append(location.getLatitude());
                sb.append("\nlontitude : ");// 经度
                sb.append(location.getLongitude());
                sb.append("\nradius : ");// 半径
                sb.append(location.getRadius());
                sb.append("\nCountryCode : ");// 国家码
                sb.append(location.getCountryCode());
                sb.append("\nCountry : ");// 国家名称
                sb.append(location.getCountry());
                sb.append("\ncitycode : ");// 城市编码
                sb.append(location.getCityCode());
                sb.append("\ncity : ");// 城市
                sb.append(location.getCity());

                baidu_loc_info = location.getCity();

                sb.append("\nDistrict : ");// 区
                sb.append(location.getDistrict());
                baidu_loc_info = baidu_loc_info+"  "+location.getDistrict();
                sb.append("\nStreet : ");// 街道
                sb.append(location.getStreet());
                sb.append("\naddr : ");// 地址信息
                sb.append(location.getAddrStr());
                sb.append("\nUserIndoorState: ");// *****返回用户室内外判断结果*****
                sb.append(location.getUserIndoorState());
                sb.append("\nDirection(not all devices have value): ");
                sb.append(location.getDirection());// 方向
                sb.append("\nlocationdescribe: ");
                sb.append(location.getLocationDescribe());// 位置语义化信息
                sb.append("\nPoi: ");// POI信息
                if (location.getPoiList() != null && !location.getPoiList().isEmpty()) {
                    for (int i = 0; i < location.getPoiList().size(); i++) {
                        Poi poi = (Poi) location.getPoiList().get(i);
                        sb.append(poi.getName() + ";");
                    }
                }
                if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                    sb.append("\nspeed : ");
                    sb.append(location.getSpeed());// 速度 单位：km/h
                    sb.append("\nsatellite : ");
                    sb.append(location.getSatelliteNumber());// 卫星数目
                    sb.append("\nheight : ");
                    sb.append(location.getAltitude());// 海拔高度 单位：米
                    sb.append("\ngps status : ");
                    sb.append(location.getGpsAccuracyStatus());// *****gps质量判断*****
                    sb.append("\ndescribe : ");
                    sb.append("gps定位成功");
                } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                    // 运营商信息
                    if (location.hasAltitude()) {// *****如果有海拔高度*****
                        sb.append("\nheight : ");
                        sb.append(location.getAltitude());// 单位：米
                    }
                    sb.append("\noperationers : ");// 运营商信息
                    sb.append(location.getOperators());
                    sb.append("\ndescribe : ");
                    sb.append("网络定位成功");
                } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                    sb.append("\ndescribe : ");
                    sb.append("离线定位成功，离线定位结果也是有效的");
                } else if (location.getLocType() == BDLocation.TypeServerError) {
                    sb.append("\ndescribe : ");
                    sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
                } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                    sb.append("\ndescribe : ");
                    sb.append("网络不同导致定位失败，请检查网络是否通畅");
                } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                    sb.append("\ndescribe : ");
                    sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
                }
//                Logger.i(sb.toString());
                loc_info.setText(baidu_loc_info);
            }
        }

    };

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        if(action_str.equals("Fragment_home")) {
            try {
                locationService.unregisterListener(mListener); //注销掉监听
                locationService.stop(); //停止定位服务
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        super.onStop();
    }

    @Override
    public void initView() {
        txt_title.setText(getString(R.string.txt_city_select));


        // 设置布局管理器
        LinearLayoutManager linearLayoutManager_sub = new LinearLayoutManager(this);
        linearLayoutManager_sub.setOrientation(LinearLayoutManager.VERTICAL);
        recycler_sub.setLayoutManager(linearLayoutManager_sub);

        // 设置适配器
        mCity_sub_Adapter = new city_sub_Adapter(context,data_sub);
        recycler_sub.setAdapter(mCity_sub_Adapter);
//        recycler_sub.addItemDecoration(new MyDecoration(context, MyDecoration.VERTICAL_LIST));
        mCity_sub_Adapter.setOnItemClickListener(new city_sub_Adapter.MyItemClickListener() {

            @Override
            public void onItemClick(View view, int postion) {
//
                TextView list_title = (TextView) view.findViewById(R.id.list_title);
                TextView list_id = (TextView) view.findViewById(R.id.list_id);

                if(action_str.equals("Fragment_home")){
                    AppUtils.putXML_area(context,main_id, list_id.getText().toString(),main_name,list_title.getText().toString());
                    EventBus.getDefault().post(new MessageEvent(Constant.ACTION_TO_CHANGECITY));
                }else{
                    EventBus.getDefault().post(new MessageEvent(
                            Constant.ACTION_city_sel,
                            main_name+" - "+list_title.getText().toString(),
                            main_id,
                            list_id.getText().toString()));
                }

                finish();

            }
        });
    }




    @Override
    public void initData() {
        toNet_getregion();
    }


    @Event(value={R.id.toback,R.id.tofinish})
    private void getEvent(View view){
        switch(view.getId()){
            case R.id.toback:
                closeActivity();
                break;
        }
    }



    private void init_List_main_type(List<getregion_bean.getregion> d){

        if(d == null)   return;
        if(d.size()<=0) return;

        type_main.removeAllViews();

        for (int a = 0; a < d.size(); a++) {
            type_main.addView(creatListItemView(d.get(a), d.get(a).id));


        }
        //设置第一个默认选中
        RelativeLayout typelayout = (RelativeLayout)type_main.getChildAt(0).findViewById(R.id.typelayout);
        typelayout.setBackgroundColor(getResources().getColor(R.color.button_huise));
    }

    private View creatListItemView(getregion_bean.getregion d, int id) {
        View convertView = LayoutInflater.from(context).inflate(R.layout.item_area_list, null);

        TextView list_title = (TextView)convertView.findViewById(R.id.list_title);
        list_title.setText(d.name);

        convertView.setId(id);
        convertView.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                int ViewID = v.getId();

                RelativeLayout typelayout = (RelativeLayout)v.findViewById(R.id.typelayout);
                typelayout.setBackgroundColor(getResources().getColor(R.color.button_huise));

                TextView list_title = (TextView)v.findViewById(R.id.list_title);

                for(int a=0;a<type_main.getChildCount();a++){
                    if(type_main.getChildAt(a).getId()!=ViewID){
                        RelativeLayout aa = (RelativeLayout)type_main.getChildAt(a).findViewById(R.id.typelayout);
                        aa.setBackgroundColor(getResources().getColor(R.color.white));
                    }
                }

                main_id   = ""+ViewID;
                main_name = ""+list_title.getText().toString();
                toNet_getregion();
            }
        });
        return convertView;
    }



    //////NET DO
    StringCallback do_getregion = new StringCallback(){


        @Override
        public void onError(Call call, Exception e, int i) {
            Logger.e(e.getMessage());
        }

        @Override
        public void onResponse(String s, int i) {
            if(hud.isShowing()){
                hud.dismiss();
            }
//            Logger.e(s);
            try{
                getregion_bean data = new Gson().fromJson(s, getregion_bean.class);

                if(data.state !=1 ){
                    T.show(context,data.msg,0);
                }else{
                    if(data.data != null){
                        if(data.data.size()>0){
                            //
                            if(main_id.isEmpty()){
                                init_List_main_type(data.data);
                            }else{
                                data_sub = data.data;
                                mCity_sub_Adapter.addItem(data_sub);
                            }

                            main_id   = ""+data.data.get(0).id;
                            main_name = ""+data.data.get(0).name;
                            toNet_getregion();
                        }
                    }

                }
            }catch (Exception e){
                e.printStackTrace();
                T.show(context,getResources().getString(R.string.alert_again),0);
            }
        }
    };
    /////NET
    private void toNet_getregion(){
        hud.show();
        JSONObject jsonBody=new JSONObject();
        try {
            jsonBody.put("device_number",         AppUtils.get_device_id(context));
            jsonBody.put("device_type",           Constant.device_type);
            jsonBody.put("token",                 AppUtils.get_token(context));
            jsonBody.put("pageName",             "category");
            jsonBody.put("serviceName",          "getregion");

            jsonBody.put("sub_id",                ""+main_id);

        } catch (JSONException e) {
            e.printStackTrace();
        }
//        Logger.i(jsonBody.toString()+" ==["+Constant.URL_register+" ]");
        HttpUtils.http_post_string(Constant.URL_getregion,jsonBody.toString(),do_getregion);
    }



























}
